<template>
  <div>
    <div class="header-left-box">
      <div class="header-logo" @click="toHome">NKU投票系统</div>
      <div class="header-right" v-if="userName">
        <el-dropdown class="dropdown-link">
          <span class="el-dropdown-link user-info-box">
            <img src="../img/defaultImg.png" class="user-avatar" alt="avatar">
            <span class="user-name">{{userName}}</span>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="userInfo">账户信息</el-dropdown-item>
            <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div v-else>
        <el-button @click="goLogin">登录</el-button>
        <el-button @click="goRegister">注册</el-button>
      </div>
    </div>
  </div>
</template>

<script>
    export default {
      name: "TopHeader",
      data(){
        return{
          userName:this.$store.state.user.userName,
        }
      },
      methods:{
        logout () {
          let _this = this
          this.$axios.post('/users/logout').then(resp => {
            if (resp.code === 200 || resp.success === true) {
              _this.$store.commit('logout')
              _this.$router.replace('/login')
            }
          }).catch(() => {
            _this.$store.commit('logout')
            _this.$router.replace('/login')
          })
        },
        userInfo(){
          if (this.$route.path !== '/admin/account/info') {
            this.$router.push('/admin/account/info')
          }
        },
        toHome(){
          this.$router.push('/home')
        },
        goLogin(){
          this.$router.push({ path: '/login', query: { tab: 'login' }})
        },
        goRegister(){
          this.$router.push({ path: '/login', query: { tab: 'register' }})
        }
      }
    }
</script>

<style scoped>
  .header-logo{
    float: left;
    margin-left: 100px;
    color: #36aaff;
    font-size: 20px;
    font-weight: 600;
  }
  .header-right{
    float: right;
    margin-right: 150px;
    display: flex;
    align-items: center;
    height: 70px;
  }
  .user-info-box {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 4px 16px 4px 8px;
    border-radius: 24px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    cursor: pointer;
    transition: box-shadow 0.2s;
  }
  .user-info-box:hover {
    box-shadow: 0 4px 16px rgba(0,0,0,0.10);
  }
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    box-shadow: 0 1px 4px rgba(0,0,0,0.08);
    border: 1px solid #eaeaea;
  }
  .user-name {
    font-size: 16px;
    color: #666;
    font-weight: 500;
    margin-left: 2px;
    letter-spacing: 0.5px;
    user-select: none;
  }
</style>
